/*
* $Id: DBStore.java 234 2010-12-29 13:37:20Z volokaleks@yandex.ru $
*
* Copyright 2008-2010 by Volokitin Alexey
* All rights reserved
*
*/
package apiary.db;

import java.util.Enumeration;
import java.util.Vector;
import javax.microedition.rms.*;

/**
 * Common interface for database.
 * Database is storage.
 * @author lexus
 */
public abstract class DBStore
{
    private RecordStore store;
    private String namedb;
    private Vector dbRecords;
    
    /**
     * Constructor
     * @param db database table name
     */
    protected DBStore(String db){
        try {
            namedb = db;
            dbRecords = new Vector();
            store = RecordStore.openRecordStore(namedb, true);
            readDB();
        } catch (RecordStoreException ex) {}
    }
    
    /**
     * Adds record in local list of it
     * @param record neww record
     * @return identificator of record
     */
    public Integer addRecord(DBRecord record){
        byte[] data = record.getData();
        Integer idRecord = null;
        dbRecords.addElement(record);
        return idRecord;
    }

    /**
     * Gets enumeration of records
     * @return enumeration of records
     */
    public Enumeration getRecordsEnumeration() {
        return dbRecords.elements();
    }

    /**
     * Gets new record
     * @return new record
     */
    public abstract DBRecord getRecord();

    /**
     * Reads database store
     */
    private void readDB() throws RecordStoreException {
        RecordEnumeration enumerator = store.enumerateRecords (null, null, false);
        while(enumerator.hasNextElement()){
            int id = enumerator.nextRecordId();
            byte[] data = store.getRecord(id);
            DBRecord record = getRecord();
            record.setData(data);
            addRecord(record);
        }
    }
}